package controller

import (
	"appengine"
	"entity"
	"fmt"
	"funcMap"
	"html/template"
	"model"
	"net/http"
	"strings"
)

func Detail(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	c.Infof("Calling detail.go")
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	//Get alias from url
	strAlias := r.URL.Path
	strAlias = strings.Replace(strAlias, "/", "", -1)
	strAlias = strings.Replace(strAlias, ".html", "", -1)

	//Get setting
	var setting entity.Setting
	if err := model.GetCurrentSetting(c, &setting); err != nil {
		fmt.Fprintln(w, "Look like you just start this application, please come admin page to setting your page !")
		return
	}
	
	//Get template
	var currentTemplate entity.Template
	if err := model.GetTemplate(c, setting.CurrentTemplateID, &currentTemplate); err != nil {
		fmt.Fprintln(w, "Look like you just start this application, no template avaiable ! Please come admin page to setting your page !")
		return
	}

	//Get news by alias
	var obj entity.News
	if err := model.GetNews(c, strAlias, &obj); err != nil {
		fmt.Fprintln(w, "This news is not exist or has been delete !")
	}

	//Get recent view
	recent, err := model.ListRecentNews(c)
	if err != nil {
		c.Errorf("Error when get Recent View at Homepage !")
	}

	//Get list category
	listCategory, err := model.ListCategory(c)
	if err != nil {
		c.Errorf("Error when get List Category at Homepage !")
	}

	//Get tag pool
	tagPool, err := model.TagPool(c)
	if err != nil {
		c.Errorf("Error when get Tag Pool at Homepage !")
	}

	var nextObj entity.News
	existNextObj, err := model.GetNextNews(c, obj, &nextObj)
	if err != nil {
		c.Errorf("No next !")
	}
	var previousObj entity.News
	existPreviousObj, err := model.GetPreviousNews(c, obj, &previousObj)
	if err != nil {
		c.Errorf("No previous !")
	}
	model.AddRecentNews(c, obj)

	funcMap := template.FuncMap{
		"GetYear":      funcMap.GetYear,
		"GetMonth":     funcMap.GetMonth,
		"GetMonthName": funcMap.GetMonthName,
		"GetDay":       funcMap.GetDay,
		"GetCategory":  funcMap.GetCategoryNews,
		"GetTag":       funcMap.GetTagNews,
		"HtmlSafe":     funcMap.HtmlSafe,
	}

	//Add data to template
	var tags string
	for _, e := range obj.Tags {
		tags += e + ","
	}
	data := map[string]interface{}{
		"obj":              obj,
		"nextObj":          nextObj,
		"existNextObj":     existNextObj,
		"previousObj":      previousObj,
		"existPreviousObj": existPreviousObj,
		"listCategory":     listCategory,
		"tagPool":          tagPool,
		"recent":           recent,
		"setting":          setting,
		"domainName":       r.Host,
	}

	//Build template
	t := template.Must(template.New("Detail").Funcs(funcMap).Parse(currentTemplate.Detail))
	if err := t.Execute(w, data); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
